﻿namespace TestTool.Tests.Common.Transport
{
    using System;
    using System.Collections.Generic;
    using System.Security.Cryptography;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    using System.Text;
    using System.Xml;
    using TestTool.HttpTransport.Interfaces;

    public class SecurityBehavior : MessageHeader, IClientMessageInspector, IEndpointBehavior
    {
        private ICredentialsProvider _credentialsProvider;
        private ProfileTokenPasswordType _passwordType = ProfileTokenPasswordType.PasswordDigest;

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(this);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (!string.IsNullOrEmpty(this.UserName))
            {
                request.Headers.Add(this);
            }
            return null;
        }

        protected string GetNonce()
        {
            byte[] data = new byte[0x10];
            RandomNumberGenerator.Create().GetBytes(data);
            return Convert.ToBase64String(data);
        }

        protected string GetPasswordHash(string nonce, string timestamp)
        {
            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
            List<byte> list = new List<byte>();
            list.AddRange(Convert.FromBase64String(nonce));
            list.AddRange(Encoding.UTF8.GetBytes(timestamp + this.Password));
            return Convert.ToBase64String(algorithm.ComputeHash(list.ToArray()));
        }

        protected string GetTimestamp()
        {
            DateTime time = this.UseUTCTimestamp ? DateTime.Now.ToUniversalTime() : DateTime.Now;
            return time.ToString("yyyy-MM-ddTHH:mm:ssZ");
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteAttributeString("xmlns", "wsse", null, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            writer.WriteAttributeString("xmlns", "wsu", null, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            if (!string.IsNullOrEmpty(this.UserName))
            {
                writer.WriteStartElement("wsse:UsernameToken");
                writer.WriteElementString("wsse:Username", this.UserName);
                if (this._passwordType == ProfileTokenPasswordType.PasswordText)
                {
                    this.WriteClearTextPassword(writer);
                }
                else
                {
                    this.WritePasswordDigest(writer);
                }
                writer.WriteEndElement();
            }
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        protected void WriteClearTextPassword(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("wsse:Password");
            writer.WriteAttributeString("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
            writer.WriteValue(this.Password);
            writer.WriteEndElement();
        }

        protected void WritePasswordDigest(XmlDictionaryWriter writer)
        {
            string nonce = this.GetNonce();
            string timestamp = this.GetTimestamp();
            string passwordHash = this.GetPasswordHash(nonce, timestamp);
            writer.WriteStartElement("wsse:Password");
            writer.WriteAttributeString("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
            writer.WriteValue(passwordHash);
            writer.WriteEndElement();
            writer.WriteElementString("wsse:Nonce", nonce);
            writer.WriteElementString("wsu:Created", timestamp);
        }

        public ICredentialsProvider CredentialsProvider
        {
            get
            {
                return this._credentialsProvider;
            }
            set
            {
                this._credentialsProvider = value;
            }
        }

        public override string Name
        {
            get
            {
                return "wsse:Security";
            }
        }

        public override string Namespace
        {
            get
            {
                return "";
            }
        }

        public string Password
        {
            get
            {
                if (this._credentialsProvider == null)
                {
                    return string.Empty;
                }
                if (this._credentialsProvider.Security != Security.WS)
                {
                    return string.Empty;
                }
                return this._credentialsProvider.Password;
            }
        }

        public ProfileTokenPasswordType PasswordType
        {
            get
            {
                return this._passwordType;
            }
            set
            {
                this._passwordType = value;
            }
        }

        public string UserName
        {
            get
            {
                if (this._credentialsProvider == null)
                {
                    return string.Empty;
                }
                if (this._credentialsProvider.Security != Security.WS)
                {
                    return string.Empty;
                }
                return this._credentialsProvider.Username;
            }
        }

        protected bool UseUTCTimestamp
        {
            get
            {
                return true;
            }
        }
    }
}

